package com.xyj.data.data_controller_demo.dataFilter.aspect;

import com.xyj.data.data_controller_demo.dataFilter.annotation.DataAllow;
import com.xyj.data.data_controller_demo.dataFilter.core.DataCheck;
import com.xyj.data.data_controller_demo.dataFilter.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author xyj
 * @date 2023/12/12
 * <p>
 * 数据过滤切面
 */
@Component
@Aspect
@Slf4j
public class DataAspect {

    @Autowired
    private DataCheck dataFilter;

    @Autowired
    private UrlUtil urlUtil;


    @Pointcut("@annotation(com.xyj.data.data_controller_demo.dataFilter.annotation.DataAllow)")
    public void dataAllow() {

    }

    @Around("dataAllow()")
    public Object modifyResult(ProceedingJoinPoint jp) throws Throwable {
        Object result = jp.proceed();


        // 先拿到被增强的方法的签名对象
        Signature signature = jp.getSignature();

        // 判断被增强的目标是否是一个方法 如果是进行强转
        if (!(signature instanceof MethodSignature ms)) {
            // 如果不是抛出自定义异常
            throw new IllegalArgumentException("该注解只能用于方法");
        }

        // 拿到目标方法
        Method method = ms.getMethod();


        // 获取method上的注解 并且拿到注解上的value值，AutoFill.class为自定义注解类
        DataAllow annotation = method.getAnnotation(DataAllow.class);
        if (annotation == null) {
            return result;
        } else {
            String urlByMethod = urlUtil.getCompleteUrlByMethod(method);
            log.info("方法url:{}", urlByMethod);
            return dataFilter.checkAndFilter(result, method, urlByMethod);
        }


    }

}
